#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <fcntl.h>
#include <netinet/tcp.h>
#include "remote_input.h"

int 
connect_remote_input_server(const char * host, short port)
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buffer[256];
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0){ 
		perror("couldn't create a socket");
		return -1;
	}
    server = gethostbyname(host);
    if (server == NULL) {
		perror("can't find the host");
		return -1;
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(port);
    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
        perror("ERROR connecting");
		return -1;
	}
	if(fcntl(sockfd, F_SETFD, O_NONBLOCK) < 0){
		perror("Couldn't put the sockfd in nonblock status");
		return -1;
	}
	int flags = 1;
	if(setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(flags)) < 0){
		perror("Couldn't set tcp_nodelay");
		return -1;
	}
    return sockfd;
}
